package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;

import com.itheima.reggie.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        //判断输入的手机号是否为空
        if (StringUtils.isNotBlank(phone)) {

            //生成验证码
            //生成4位数的随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            System.out.println(code);

            //发送验证码
           // SMSUtils.sendMessage(phone,code);

            //将验证码存到session中
            session.setAttribute(phone,code);

            return R.success(null);
        }
        return R.error("短信发送失败");

    }

    @PostMapping("/login")
    public R login(@RequestBody User user,HttpSession session){
        //获取手机号和验证码
        String phone = user.getPhone();
        String code = user.getCode();
        //判断验证码是否正确
        if (code.equals(session.getAttribute(phone)) ){
            //查询手机号
         User u =   userService.findPhone(phone);
         //设置登录成功标记
         session.setAttribute("user",u.getId());

            return R.success(u);
        }

        return R.error("登录失败");



    }

}
